<style lang="scss" scoped>
.body {
  width: 100%;
  padding: 20px;

  .pagination-container {
    padding: 0;
  }

  .condition-container{
    .el-form-item.el-form-item--medium {
      margin-right: 30px;
      margin-bottom: 0;
    }
  }
  .el-table {
    border: none;

    .el-table__header-wrapper {
      .el-table__cell{
        background-color: #F5F7FA;
      }

      .el-table__cell  {
        .cell {
          color: #333333;
        }
      }
    }

    .el-table__body-wrapper {
      .el-table__row {
        .cell {
          color: #333333;
        }
      }
    }

    .el-table-column--selection{
      .cell {
        text-align: center;
      }
    }
  }

  .arrangement {
    .list {
      border: 1px solid #dfe6ec;
      border-right: none;
      border-bottom: none;
      background-color: #fff;
      //padding: 20px;
    }
  }
  .content {
    .name {
      display: flex;
      margin-bottom: 20px;
      .lable {
        width: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
  .garbageCan {
    display: flex;
    margin-bottom: 20px;
  }
  .header-warp {
    margin: 20px 0;
    display: flex;
    justify-content: space-between;
  }
  .search-box {
    margin: 0 30px;
    .search-warp {
      display: flex;
      align-items: center;
      padding: 10px;
      .title {
        color: #8e8e8e;
        margin-right: 10px;
      }
    }
  }
  .icnoTitle {
    margin-left: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .displayNone {
    display: none;
  }
}
</style>

<script>
import {
  stationCreate,
  stationDelete,
  stationUpdate,
  stationDel
} from '@/api/station'
import { getPosition, getDept } from '@/api/basic'
import Pagination from '@/components/Pagination'
import DialogContent from '@/components/DialogContent/index.vue'
import { treeToArray } from '@/utils'
export default {
  components: {
    Pagination,
    DialogContent
  },
  data() {
    return {
      isBatchDeleting: false,
      selectedRows: [],
      list: [],
      jobSearch: '',
      addDialogVisible: false,
      ruleForm: {
        input: '',
        value: ''
      },
      type: 'add',
      id: '',
      total: 0,
      paginate: 10,
      page: 1,
      lastPage: '',
      state: 'normal',
      delete: 0,
      dept: [],
      isSelectAll: false,
      rules: {
        input: [
          { required: true, message: '请输入职位名称', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ]
      },
      users: []
    }
  },
  computed: {
    allDepartment() {
      return treeToArray(this.dept)
    }
  },
  created() {
    this.getdata()
  },
  methods: {
    async handleSelectionChange(e) {
      this.selectedRows = e
      await this.$nextTick()
      if (this.isSelectAll) {
        this.list.map(item => {
          this.$refs.multipleTable.toggleRowSelection(item, true)
        })
      }
    },
    handleUseSelectAll(selection) {
      this.isSelectAll = !this.isSelectAll
    },
    async batchDelete(isDelete = false) {
      try {
        const flag = this.state === 'delete' && isDelete

        const tips = !isDelete ? '是否恢复职位名称' : '是否删除职位名称?'
        await this.$confirm(tips, '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        this.isBatchDeleting = true

        const stationDeleteWithErrHandler = async(row) => {
          const data = await stationDelete(row.id)
          if (data.code !== 201) { throw new Error(result.message ?? '删除职位名称失败') }

          return data
        }

        const stationDelWithErrHandler = async(row) => {
          const data = await stationDel(row.id)
          if (data.code !== 201) { throw new Error(result.message ?? '删除职位名称失败') }
        }

        if (flag) {
          const result = await Promise.allSettled(this.selectedRows.map(item => stationDeleteWithErrHandler(item)))
          const failedTasks = result.filter(item => item.status === 'rejected')

          if (failedTasks.length >= this.selectedRows.length) {
            this.$message.error('删除职位失败')
          } else {
            this.$message.success(`成功删除${this.selectedRows.length - failedTasks.length}个职位`)
          }
        } else {
          const result = await Promise.allSettled(this.selectedRows.map(item => stationDelWithErrHandler(item)))
          const failedTasks = result.filter(item => item.status === 'rejected')

          if (failedTasks.length >= this.selectedRows.length) {
            this.$message.error('删除职位失败')
          } else {
            this.$message.success(`成功删除${this.selectedRows.length - failedTasks.length}个职位`)
          }
        }

        this.selectedRows = []
        this.isBatchDeleting = false
        this.getdata()
      } catch (e) {
        if (e === 'cancel') { return }

        this.selectedRows = []
        this.isBatchDeleting = false

        if (e instanceof Error) {
          this.$message.error(e.message)
        }
      }
    },
    async getdata() {
      const params = {
        name: this.jobSearch,
        paginate: this.paginate,
        page: this.page,
        delete: this.delete
      }
      try {
        const { data } = await getPosition(params)
        const res = await getDept()
        this.list = data.data
        this.total = data.total
        this.lastPage = data.last_page
        this.dept = res.data
      } catch (error) {
        this.$message.error('获取职位信息失败')
      }
    },
    getdelete() {},
    handleEdit(index, row) {
      console.log(row)
      this.ruleForm.input = row.name
      this.id = row.id
      this.ruleForm.value = this.getParentDepartment(row?.department?.id)
      this.type = 'edit'
      this.addDialogVisible = true
    },
    async handleDelete(index, row, type = 'qita') {
      try {
        await this.$confirm(
          type == 'huifu' ? '是否恢复职位名称' : '是否删除职位名称?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        if (this.state == 'normal' || type == 'huifu') {
          const res = await stationDel(row.id)
          if (res.code == '201') {
            this.getdata()
            this.$message({
              type: 'success',
              message: type == 'huifu' ? '恢复成功' : '删除成功!'
            })
          }
        } else {
          const res = await stationDelete(row.id)
          if (res.code == '201') {
            this.getdata()
            this.$message({
              type: 'success',
              message: '彻底删除成功!'
            })
          }
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: type == 'huifu' ? '恢复失败' : '删除失败'
        })
      }
      // this.$confirm(
      //   type == 'huifu' ? '是否恢复职位名称' : '是否删除职位名称?',
      //   '提示',
      //   {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }
      // )
      //   .then(() => {
      //     if (this.state == 'normal' || type == 'huifu') {
      //       stationDel(row.id)
      //         .then((res) => {
      //           console.log(res)
      //           if (res.code == '201') {
      //             this.getdata()
      //             this.$message({
      //               type: 'success',
      //               message: type == 'huifu' ? '恢复成功' : '删除成功!'
      //             })
      //           }
      //         })
      //         .catch((err) => {
      //           this.$message({
      //             type: 'info',
      //             message: type == 'huifu' ? '恢复失败' : '删除失败'
      //           })
      //         })
      //     } else {
      //       stationDelete(row.id)
      //         .then((res) => {
      //           if (res.code == '201') {
      //             this.getdata()
      //             this.$message({
      //               type: 'success',
      //               message: '彻底删除成功!'
      //             })
      //           }
      //         })
      //         .catch((err) => {
      //           this.$message({
      //             type: 'info',
      //             message: '删除失败'
      //           })
      //         })
      //     }
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: type == 'huifu' ? '已取消恢复' : '已取消删除'
      //     })
      //   })
    },
    search() {
      this.getdata()
    },
    resetSearchInfo() {
      this.page = this.$options.data().page
      this.jobSearch = this.$options.data().jobSearch
      this.getdata()
    },
    newPosition() {
      this.type = 'add'
      this.addDialogVisible = true
      this.ruleForm.input = ''
      this.ruleForm.value = ''
    },
    append() {
      if (!this.ruleForm.input) {
        return this.$message({
          type: 'info',
          message: '请输入职位名称'
        })
      }
      if (!this.ruleForm.value) {
        return this.$message({
          type: 'info',
          message: '请选择绑定部门'
        })
      }
      if (this.type == 'add') {
        stationCreate({
          name: this.ruleForm.input,
          department_id: this.ruleForm.value[this.ruleForm.value.length - 1]
        })
          .then((res) => {
            console.log(res)
            if (res.code == 201) {
              this.ruleForm.input = ''
              this.ruleForm.value = ''
              this.getdata()
              this.addDialogVisible = false
              this.$message({
                type: 'success',
                message: '新增职位成功'
              })
            }
          })
          .catch((err) => {})
      } else {
        stationUpdate(
          `name=${this.ruleForm.input}&id=${this.id}&department_id=${
            this.ruleForm.value[this.ruleForm.value.length - 1]
          }`
        )
          .then((res) => {
            console.log(res)
            if (res.code == 201) {
              this.ruleForm.input = ''
              this.ruleForm.value = ''
              this.getdata()
              this.addDialogVisible = false
              this.$message({
                type: 'success',
                message: '修改职位成功'
              })
            }
          })
          .catch((err) => {})
      }
    },
    cancel() {
      this.ruleForm.input = ''
      this.ruleForm.value = []
      this.addDialogVisible = false
    },
    handleCurrentChange(val) {
      this.paginate = val.limit
      this.page = val.page
      this.getdata()
    },
    restorePost(val) {
      this.page = 1
      if (val == 'delete') {
        this.$set(this, 'state', 'delete')
        this.delete = 1
        this.getdata()
        console.log(this.state)
      } else {
        this.$set(this, 'state', 'normal')
        this.delete = ''
        this.getdata()
        console.log(this.state)
      }
    },
    handleChange(val) {
      console.log(val, this.ruleForm.value)
    },
    leaveFor() {
      this.$router.push('/dept/list')
    },

    getParentDepartment(departmentId) {
      const allDepartments = this.allDepartment
      const result = []
      function findParent(id) {
        const department = allDepartments.find(dep => dep.id === id)
        console.log('department --------->', department)
        if (department) {
          result.unshift(department.id)
          if (department.parent_id !== null) {
            findParent(department.parent_id)
          }
        }
      }

      findParent(departmentId)
      console.log('result --------->', result)
      return result
    },

    handleWatchUsers(row) {
      this.users = row.users
    }
  }
}
</script>

<template>
  <div class="body">
    <div class="arrangement">
      <!-- <div class="garbageCan">
        <div class="header-warp">
          <el-button text type="primary" icon="el-icon-plus" @click="newPosition()">
            新增职位
          </el-button>
          <el-button v-if="state == 'normal'" type="primary" icon="el-icon-delete" @click="restorePost('delete')">垃圾桶</el-button>
          <el-button v-else type="primary" icon="el-icon-user" @click="restorePost('normal')">职位列表</el-button>
        </div>
        <el-row class="search-box">
          <el-col>
            <div class="search-warp">
              <div class="title">职位名称</div>
              <div>
                <el-input v-model="jobSearch" placeholder="请输入职位名称" clearable class="search-ipt" @clear="search" />
              </div>
              <div class="search-warp">
                <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
                <el-button type="danger" @click="resetSearchInfo">重置</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div> -->
      <el-card style="margin-bottom: 20px;border: none;" shadow="never">
        <div class="condition-container">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="职位名称">
              <el-input v-model="jobSearch" clearable placeholder="请输入职位名称" @clear="search" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
              <el-button @click="resetSearchInfo">重置</el-button>

            </el-form-item>
          </el-form>

        </div>
      </el-card>
      <el-card shadow="never" style="border: none;">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-button icon="el-icon-plus" type="primary" @click="newPosition()">添加职位</el-button>
          </el-form-item>

          <el-form-item>
            <el-button v-if="state == 'normal'" icon="el-icon-delete" @click="restorePost('delete')">回收站</el-button>
            <el-button v-else @click="restorePost('normal')">职位列表</el-button>
          </el-form-item>

          <el-form-item>
            <el-button
              :loading="isBatchDeleting"
              :disabled="selectedRows.length <= 0 || isBatchDeleting"
              @click="batchDelete(true)"
            >
              ({{ selectedRows.length }})批量删除
            </el-button>

            <el-button
              v-if="state === 'delete'"
              :loading="isBatchDeleting"
              :disabled="selectedRows.length <= 0 || isBatchDeleting"
              @click="batchDelete()"
            >
              ({{ selectedRows.length }})批量恢复
            </el-button>
          </el-form-item>
        </el-form>
        <div class="list">
          <el-table
            ref="multipleTable"
            :data="list"
            row-key="id"
            border
            @selection-change="handleSelectionChange"
            @select-all="handleUseSelectAll"
          >
            <el-table-column type="selection" />
            <el-table-column label="职位名称" prop="name" align="center" />
            <el-table-column label="部门名称" prop="department.name" align="center" />
            <el-table-column label="职位人员" prop="department.name" align="center">
              <template v-slot="{ row }">
                <div v-if="!row.users">-</div>
                <el-popover
                  v-else
                  placement="top-start"
                  title="当前职位人员"
                  width="200"
                  trigger="click"
                >
                  <el-button
                    slot="reference"
                    type="text"
                  >
                    查看
                  </el-button>
                  <template>
                    <div>
                      <el-tag
                        v-for="item in row.users"
                        :key="item.id"
                        style="margin: 0 10px 10px 0;"
                      >
                        {{ item?.user?.username }}
                      </el-tag>
                    </div>
                  </template>
                </el-popover>
                <!--                <el-button type="text" @clik="handleWatchUsers(row)">查看</el-button>-->
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <!-- <el-button :class="{ displayNone: state != 'normal' }" circle plain type="primary" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)" /> -->
                <el-button :class="{ displayNone: state != 'normal' }" type="text" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                <el-button v-if="state != 'normal'" class="buttonDiv" type="text" @click="handleDelete(scope.$index, scope.row, 'huifu')">恢复</el-button>
                <!-- <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.$index, scope.row)" /> -->
                <el-button type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div>
          <Pagination layout="sizes, total, prev, pager, next, jumper" :total="total" :limit="paginate" @pagination="handleCurrentChange" />
        </div>
      </el-card>
      <DialogContent
        :close-on-click-modal="false"
        :title="type == 'add' ? '新增职位名称' : '修改职位名称'"
        :visible.sync="addDialogVisible"
        width="35%"
        center
      >
        <el-form v-if="dept.length>0" :model="ruleForm" :rules="rules" :inline="true">

          <el-form-item label="职位名称" prop="input">
            <el-input
              v-model="ruleForm.input"
              style="width: 300px"
              placeholder="请输入职位名称"
            />
          </el-form-item>

          <el-form-item label="部门名称" prop="value">
            <el-cascader
              v-model="ruleForm.value"
              clearable
              style="width: 300px"
              :options="dept"
              :props="{
                checkStrictly: true,
                expandTrigger: 'hover',
                label: 'name',
                value: 'id',
              }"
              :show-all-levels="false"
              @change="handleChange"
            />
          </el-form-item>

        </el-form>
        <div v-else class="content">
          <div style="text-align:center;width:100%;font-size: 15px;">
            <span>请先创建部门在创建职位</span>
            <a style="text-decoration: underline;color:red" @click="leaveFor">点击前往</a>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel()">取 消</el-button>
          <el-button type="primary" @click="append()">确 定</el-button>
        </span>
      </DialogContent>
    </div>
  </div>
</template>
